package com.dwxt.sport.business.service;

import com.dwxt.common.base.StatusCode;
import com.dwxt.common.constant.VariableConstants;
import com.dwxt.common.util.SnowIdUtil;
import com.dwxt.sport.business.dao.DeformitySportsHealthEquipmentMapper;
import com.dwxt.sport.business.dao.DeformitySportsHealthMapper;
import com.dwxt.sport.business.entity.DeformitySportsHealth;
import com.dwxt.sport.business.entity.DeformitySportsHealthEquipment;
import com.dwxt.sport.business.vo.deformitySportsHealth.InsertOrUpdateDeformityEquipmentVo;
import com.dwxt.sport.business.vo.deformitySportsHealth.InsertOrUpdateDeformitySportsHealthVo;
import com.dwxt.sport.business.vo.deformitySportsHealth.SelectDeformitySportsHealthVo;
import com.dwxt.sport.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * 残疾人运动健康
 *
 * @author Kuang.JiaZhuo
 * @date 2020-07-30 14:46
 */
@Service
public class DeformitySportsHealthService {

    @Resource
    DeformitySportsHealthMapper deformitySportsHealthMapper;

    @Resource
    DeformitySportsHealthEquipmentMapper equipmentMapper;

    /**
     * @方法名：insertOrUpdateDeformitySportsHealth
     * @描述： 新增或修改残疾人运动健康
     * @作者： kjz
     * @日期： Created in 2020/7/30 16:10
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertOrUpdateDeformitySportsHealth(InsertOrUpdateDeformitySportsHealthVo insertOrUpdateVo) {

        String id = insertOrUpdateVo.getId();

        DeformitySportsHealth sportsHealth = new DeformitySportsHealth()
                .setName(insertOrUpdateVo.getName()) //设备名称
                .setUnitType(insertOrUpdateVo.getUnitType()) //设备型号
                .setRecommendedCoverage(insertOrUpdateVo.getRecommendedCoverage()); //建议覆盖率

        if(null==id || id.trim().length()==0){
            //新增
            sportsHealth.setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now()).setIsDelete(VariableConstants.STRING_CONSTANT_0)
                    .setStreetId(insertOrUpdateVo.getStreetId()); //街道id
            return deformitySportsHealthMapper.insert(sportsHealth);
        }else{
            //更新
            sportsHealth.setUpdateTime(LocalDateTime.now()).setId(id);
            return deformitySportsHealthMapper.updateByPrimaryKeySelective(sportsHealth);
        }

    }

    /**
     * @方法名：selectDeformitySportsHealthByCriteria
     * @描述： 按条件查询残疾人运动健康列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/7/30 16:11
     */
    public PageInfo<DeformitySportsHealth> selectDeformitySportsHealthByCriteria(SelectDeformitySportsHealthVo selectVo) {
        PageHelper.startPage(selectVo.getPageNum(), selectVo.getPageSize());
        List<DeformitySportsHealth> list = deformitySportsHealthMapper.selectDeformitySportsHealthByCriteria(selectVo);
        PageInfo<DeformitySportsHealth> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * @方法名：deletetDeformitySportsHealthByIds
     * @描述： 根据ids批量删除残疾人运动健康
     * @作者： kjz
     * @日期： Created in 2020/7/30 16:11
     */
    @Transactional(rollbackFor = Exception.class)
    public int deletetDeformitySportsHealthByIds(String ids) {
        if(ids == null || "".equals(ids)) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        String[] idArray = ids.split(",");

        return this.deformitySportsHealthMapper.deletetDeformitySportsHealthByIds(idArray);
    }


    /******************************************************************  关联设备  ******************************************************************************/

    /**
     * @方法名：insertOrUpdateRelationEquipment
     * @描述： 新增 或 更新【残疾人运动健康】设备关联
     * @作者： kjz
     * @日期： Created in 2020/7/30 16:11
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertOrUpdateRelationEquipment(InsertOrUpdateDeformityEquipmentVo insertOrUpdateVo) {

        String id = insertOrUpdateVo.getId();

        DeformitySportsHealthEquipment healthEquipment = new DeformitySportsHealthEquipment()
                .setEquipmentId(insertOrUpdateVo.getEquipmentId()) //设备id
                .setCumulativePerson(insertOrUpdateVo.getCumulativePerson()) //累计人次
                .setAvg(insertOrUpdateVo.getAveragePeople()) //平均人次
                .setTodayPeople(insertOrUpdateVo.getTodayPeople()) //今日人次
                .setTotalUsageTime(insertOrUpdateVo.getTotalUsageTime()) //使用总时长(单位:min)
                .setRemark(insertOrUpdateVo.getRemark()) //备注
                .setDeviceStates(insertOrUpdateVo.getDeviceStates()); //设备状态

        int result = 0;
        String healthId = insertOrUpdateVo.getHealthId();
        if (null == id || id.trim().length() == 0) {
            //新增
            if (null == healthId || healthId.trim().length() == 0) {
                throw new CustomException(StatusCode.HEALTH_ID_IS_NULL);
            }
            healthEquipment.setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now()).setIsDelete(VariableConstants.STRING_CONSTANT_0)
                    .setHealthId(insertOrUpdateVo.getHealthId()); //残疾人运动健康关联id
            result = equipmentMapper.insert(healthEquipment);

        } else {
            //更新
            healthEquipment.setUpdateTime(LocalDateTime.now()).setId(id);
            result = equipmentMapper.updateByPrimaryKeySelective(healthEquipment);
        }

        if(result>0){
            this.updateDeformitySportsHealth(healthId);
        }

        return result;
    }

    /**
     * @方法名：updateDeformitySportsHealth
     * @描述： 新增或更新关联设备成功后更新残疾人运动健康需要计算的数据
     * @作者： kjz
     * @日期： Created in 2020/8/4 15:37
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateDeformitySportsHealth(String healthId) {
        HashMap map = equipmentMapper.selectStatisticsByHealthId(healthId);
        DeformitySportsHealth deformitySportsHealth = new DeformitySportsHealth()
                .setAmount(Integer.valueOf(map.get("amount").toString()))
                .setTotalPersonTimes(Integer.valueOf(map.get("totalPersonTimes").toString()))
                .setAvg(Double.parseDouble(map.get("avgElapsedTime").toString()))
                .setUpdateTime(LocalDateTime.now())
                .setId(healthId);
        return deformitySportsHealthMapper.updateByPrimaryKeySelective(deformitySportsHealth);
    }

    /**
     * @方法名：deleteRelationEquipmentByIds
     * @描述： 根据ids批量删除【残疾人运动健康】设备关联
     * @作者： kjz
     * @日期： Created in 2020/7/30 16:12
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteRelationEquipmentByIds(String ids) {
        if(ids == null || "".equals(ids)) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        String[] idArray = ids.split(",");

        int result = this.equipmentMapper.deleteRelationEquipmentByIds(idArray);
        if(result>0){
            String id = idArray[0];
            String healthId = equipmentMapper.selectByPrimaryKey(id).getHealthId();
            this.updateDeformitySportsHealth(healthId);
        }
        return result;
    }

    /**
     * @方法名：selectRelationEquipmentByCriteria
     * @描述： 根据【残疾人运动健康】的id查询关联设备的列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/7/30 16:13
     */
    public PageInfo<DeformitySportsHealthEquipment> selectRelationEquipmentByCriteria(Integer pageNum, Integer pageSize, String healthId) {
        PageHelper.startPage(pageNum==null?1:pageNum, pageSize==null?10:pageSize);
        List<DeformitySportsHealthEquipment> list = equipmentMapper.selectRelationEquipmentByCriteria(healthId);
        PageInfo<DeformitySportsHealthEquipment> pageInfo = new PageInfo(list);
        return pageInfo;
    }
}
